<?php

namespace common\service;


use common\exception\LogicException;
use common\model\MediaModel;
use common\model\UserAuthenticationModel;
use support\ErrorCode;
use think\Exception;

class UserAuthenticationService
{


    /**
     * 重写查询
     * @param $param
     * @return array
     */
    public function find($param)
    {
        $userAuthenticationModel = model(UserAuthenticationModel::class);
        $res = [];
        $data = $userAuthenticationModel->where($param['filter'])->find();
        if (empty($data)) {
            return null;
        }
        $jsonFields = json_decode($data['json'] ?? '{}', true);
        $data = CommonService::getFormatAttrData(model(UserAuthenticationModel::class), $data);

        $mediaFrontOfIdId = $jsonFields['media_front_of_id'] ?? 0;
        $mediaReverseOfIdId = $jsonFields['media_reverse_of_id'] ?? 0;


        $mediaIds = [$mediaFrontOfIdId, $mediaReverseOfIdId];
        $userAuthenticationModel->emptyComplexFilterRelatedModule();
        $mediaData = model(MediaModel::class)->where(['id' => ['IN', implode(',', $mediaIds)]])->select();
        $mediaData = array_column($mediaData, null, 'id');

        $mediaData = array_map(function ($item) {

            foreach ($item as $key => &$mediaVal) {
                $mediaVal = model(MediaModel::class)->getComplexAttr($key, $mediaVal, 'media');
            }
            unset($mediaVal);
            return $item;
        }, $mediaData);

        $res['user_authentication'] = $data;
        $res['media_front_of_id'] = $mediaData[$mediaFrontOfIdId] ?? null;
        $res['media_reverse_of_id'] = $mediaData[$mediaReverseOfIdId] ?? null;
        return $res;
    }

    /**
     * 提交认证
     * @param $data
     * @return array
     * @throws \Throwable
     */
    public function submit($data)
    {
        $mediaService = new MediaService();
        $userAuthenticationModel = model(UserAuthenticationModel::class);
        $mediaModel = model(MediaModel::class);
        $currentModuleLinkRelation = $userAuthenticationModel->parserFilterModuleRelation(true);

        $userAuthenticationModel->startTrans();
        try {
            $relationIds = [];
            foreach ($data as $moduleCode => $item) {
                if (empty($item)) {
                    continue;
                }
                if (array_key_exists($moduleCode, $currentModuleLinkRelation)) {

                    switch ($currentModuleLinkRelation[$moduleCode]['module_code']) {
                        case "media":
                            $mediaIds = [];
                            if (!is_many_dimension_array($item)) {
                                $item = [$item];
                            }
                            foreach ($item as $mediaItem) {
                                if (empty($mediaItem)) {
                                    continue;
                                }
                                $mediaService->generateMediaData($mediaItem);
                                $mediaData = $mediaModel->addItem($mediaItem);
                                if (!$mediaData) {
                                    throw new LogicException($mediaModel->getError(), ErrorCode::MEDIA_ADD_FAILURE);
                                }
                                $mediaIds[] = $mediaData['id'];
                            }
                            $relationIds[$moduleCode] = join(',', $mediaIds);
                            break;
                    }
                }
            }
            // 把水平自定义关联数据回插入主表
            foreach ($relationIds as $field => $relationId) {
                $data['user_authentication'][$field] = $relationId;
            }
            //不允许传递status,reasons_for_failure字段
            unset($data['user_authentication']['reasons_for_failure']);
            $data['user_authentication']['status'] = 'to_be_reviewed';

            $commonService = CommonService::instance('user_authentication');


            // 存在id
            if (isset($data['user_authentication']['id']) && $data['user_authentication']['id'] > 0) {
                $data['user_authentication']['fdd_auth_status'] = 0;
                $data['user_authentication']['fdd_transaction_no'] = "";
                $data['user_authentication']['fdd_auth_url'] = "";
                $data['user_authentication']['fdd_auth_status_desc'] = "";
                $data['user_authentication']['fdd_cert_status'] = 0;
                $resData = $commonService->update($data['user_authentication']);
            } else {
                $resData = $commonService->create($data['user_authentication']);
            }

            $userAuthenticationModel->commit();
            return $resData;
        } catch (\Throwable $e) {
            $userAuthenticationModel->rollback();
            throw $e;
        }
    }
}
